<script setup>

import {ElButton, ElCard, ElInput, ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Refresh} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {userInfoStore} from "@/store/userInfoStore.js";
import AddQuestionComponent from "@/components/admin/questionAdmin/AddQuestionComponent.vue";
import UpdateAppComponent from "@/components/admin/questionAdmin/UpdateQuestionComponent.vue";
import {DeleteQuestion, ListQuestionsByPage} from "@/api/question.js";
import router from "@/router/index.js";

const current = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(20) //总条数
//分页条数据模型
const form = ref({
  id: null, // 题目Id
  questionContent:'',//题目内容
  appId: null,//appid
  userId: null,//用户id
  notId:null,//不需要的id
  sortField: '',//排序字段
  sortOrder: '',//排序顺序
  isDelete: null
})
const fields = ref(
  {
          "题目ID":"id",
          "AppId":"appId",
          "用户Id":"userId",
          "题目内容":"questionContent",
      }
)
const tableData = ref([])

const clearForm = () => {
  form.value={
    id: null, //题目id
    questionContent:'',//题目内容
    appId: null,//appid
    userId: null,//用户id
    notId:null,//不需要的id
    sortField: '',//排序字段
    sortOrder: '',//排序顺序
    isDelete: null
  };
  current.value = 1;
  pageSize.value = 10;
}

const fetchQuestionList = async () => {
  const params = {
    id: (form.value.id!=null&&form.value.id>0)?form.value.id:null,
    questionContent:form.value.questionContent ===''?null:form.value.questionContent,
    appId: (form.value.appId&&form.value.appId>0)?form.value.appId:null,//appid
    userId: (form.value.userId&&form.value.userId>0)?form.value.userId:null,//用户id
    notId:(form.value.notId&&form.value.notId>0)?form.value.notId:null,//不需要的id
    sortField:  form.value.sortField ===''?null:form.value.sortField,//排序字段
    sortOrder:  form.value.sortOrder ===''?null:form.value.sortOrder,//排序顺序
    current: current.value,
    pageSize: pageSize.value,
    isDelete: (form.value.isDelete&&form.value.isDelete>=0)?form.value.isDelete:null
  }
  //获取用户列表 todo 获取列表的函数改一下
  const answer = await ListQuestionsByPage(params);
  ElMessage.success("搜索成功！");
  console.log("answer: ",answer);
  tableData.value = answer.data.questionContent||[];
  total.value = answer.data.total;
  current.value = answer.data.current;
  pageSize.value = answer.data.pageSize;
  console.log("tableData: ",tableData.value)
}
// todo 改
onMounted(async ()=>{
  await fetchQuestionList();
  console.log("Question_List:",tableData.value)
})
//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  pageSize.value = size;
  await fetchQuestionList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  current.value = num;
  await fetchQuestionList()
};


//删除用户
const DeleteForQuestion = async (row)=>{
  ElMessageBox.confirm(
      row.isDelete===0?'此操作将删除该题目，是否确认删除？':'此操作将恢复该题目，是否确认恢复？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        console.log(row.id)
        await DeleteQuestion(row.id);
        await fetchQuestionList();
        if(row.isDelete===0) {
          ElMessage.success("删除成功！")
        }else{
          ElMessage.success("恢复成功！")
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '按钮取消!',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>题目管理</span>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline class="user-list">
      <!--todo 这里要与后端的搜索用户的数据一致，添加一样多的搜索框 -->
<!--      <el-form-item label="用户ID：">-->
<!--        <el-input v-model="form.id" />-->
<!--      </el-form-item>-->
      <el-form-item label="应用id：">
        <el-input v-model="form.appId" />
      </el-form-item>
      <el-form-item label="用户id：">
        <el-input v-model="form.userId" />
      </el-form-item>
      <el-form-item label="题目内容：">
        <el-input v-model="form.questionContent" />
      </el-form-item>
      <el-form-item label="排序字段：">
        <el-select placeholder="请选择" v-model="form.sortField" style="width: 240px">
          <el-option v-for="([label, value]) in Object.entries(fields)" :key="value" :label= "label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目状态：">
        <el-select placeholder="请选择" v-model="form.isDelete" style="width: 240px">
          <el-option label="所有" value=-1></el-option>
          <el-option label="正常" value=0></el-option>
          <el-option label="已删除" value=1></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式：">
        <el-select placeholder="请选择" v-model="form.sortOrder" style="width: 240px">
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="button-group">
        <!-- todo 改 -->
        <el-button type="primary" @click="fetchQuestionList"
        >搜索</el-button
        >
        <el-button
            @click="
            clearForm();
            fetchQuestionList();
            ElMessage.success('重置成功！')
          "
        >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          type="index"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
          label="题目ID"
          prop="id"
      ></el-table-column>
      <el-table-column
          label="题目内容"
          prop="questionContent"
          width="480px"
      ></el-table-column>
      <el-table-column
          label="应用id"
          prop="appId"
      ></el-table-column>
      <el-table-column label="用户id" prop="userId">
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
      <el-table-column label="状态" prop="isDelete">
        <template #default="{ row }">
          <el-text class="mx-1" type="success" v-if="row.isDelete === 0">正常</el-text>
          <el-text class="mx-1" type="danger" v-else>已删除</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
       <template #default="{ row }">
         <el-button
             :icon = Edit
             circle
             plain
             type="primary"
             @click="router.push(`/add/question/${row.appId}`)" >  </el-button>
         <UpdateAppComponent ref="updateQuestionRef" @call-parent="fetchQuestionList"/>
         <el-button
             :icon="Delete"
             circle
             plain
             type="danger"
             @click="DeleteForQuestion(row)"
             v-if="row.isDelete === 0"
         ></el-button>
         <el-button
             :icon="Refresh"
             circle
             plain
             type="success"
             @click="DeleteForQuestion(row)"
             v-if="row.isDelete === 1"
         ></el-button>
       </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="form.current"
        v-model:page-size="form.pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .user-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; /* 表单项之间的间距 */
    align-items: center;
  }

  .user-list el-form-item {
    margin-bottom: 0; /* 移除默认的底部间距 */
  }

  .button-group {
    margin-left: auto; /* 将按钮组推到右侧 */
  }

  el-image {
    position: relative;
    z-index: 1;
  }
  .el-image-viewer__img {
    z-index: 9999 !important;
  }
}
</style>


